var express = require('express');
var router = express.Router();
const multer = require('multer')
var db = require("../db"); //引入数据库封装模块
var vertoken = require('./token.js')


const log4js= require('../utils/log4js/log.js')
const logger = log4js.getLogger()//根据需要获取logger
const errlogger = log4js.getLogger('err')
const othlogger = log4js.getLogger('oth')

let upload = multer({
  limits: {
    //限制文件大小10kb
    fileSize: 10 * 1000,
    //限制文件数量
    files: 5
  },
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
      // if (file) {
      cb(null, './uploads/');
      // }
    },
    filename: function (req, file, cb) {
      // if (file) {
      var changedName = (new Date().getTime()) + '-' + file.originalname;
      cb(null, changedName);
      // }
    }
  }),
  fileFilter: function (req, file, cb) {
    // 限制文件上传类型，仅可上传png格式图片
    if (file.mimetype == 'image/png') {
      cb(null, true)
    } else {
      cb(null, false)
    }
  }
});


router.get('/home1', function (req, res, next) {
  // logger.info("这是日志:"+22222);  logger.info即可记录日志
  // errlogger.error('出错了, 没有姓名', req.query)
  //   othlogger.info('其他日志信息')
  var a="1111";
  var b="222";
  db.query("SELECT * FROM USERS", [], function (err, results, fields) {
    
    res.json({
      status: 200,
      data: results
    })
  })
});


router.post('/home2', function (req, res, next) {
  db.query("select * from users where name=?", [req.query.name], function (err, results, fields) {
    res.json({
      status: 200,
      data: results
    })
  })

});


router.post('/home3', function (req, res, next) {
  db.query("insert into users(name,address) values(?,?)", [req.body.name, req.body.address], function (err, results, fields) {
    if (err) {
      res.json({
        status: '错误',
        data: err
      })
    } else {
      res.json({
        status: 200,
        data: '成功'
      })
    }


  })
});


router.put('/home4/:id', function (req, res, next) {
  console.log(req.params.id,"req");
  db.query("update  users set name='王尼玛',address='天堂' where id=" + req.params.id, function (err, results, fields) {
    if (err) {
      res.json({
        status: '错误',
        data: err
      })
    } else {
      res.json({
        status: 200,
        data: '成功'
      })
    }


  })
});


router.delete('/home5/:id', function (req, res, next) {
  db.query("delete from   users where  id=" + req.params.id, function (err, results, fields) {
    if (err) {
      res.json({
        status: '错误',
        data: err
      })
    } else {
      res.json({
        status: 200,
        data: '成功'
      })
    }
  })
});


router.post('/home6', function (req, res, next) {
  //如果你要执行多条sql语句，则需要：  包含回滚操作
  var sqlParamsEntity = [];
  var sql1 = `insert into users(name,address)  VALUES('burt',19)`;
  sqlParamsEntity.push(db._getNewSqlParamEntity(sql1));
  sql1 = `insert into users(name,address)  VALUES('burt',19)`;
  sqlParamsEntity.push(db._getNewSqlParamEntity(sql1))
  sql1 = `insert into users(name,address)  VALUES('burt',19)`;
  sqlParamsEntity.push(db._getNewSqlParamEntity(sql1))


  db.execTrans(sqlParamsEntity, function (err) {
    if (err) {
      // logger.info("报错了兄弟",err);
      res.json({
        status: 200,
        data: '执行失败'
      })
    } else {
      res.json({
        status: 200,
        data: '执行成功'
      })
    }
  });
});


let multerUpload = upload.array('multerFile');
router.post('/uploadImage', (req, res) => {
  multerUpload(req, res, (err) => {
    if (!!err) {
      res.json({
        code: '2000',
        type: 'multer',
        fileList: [],
        msg: err.message
      });
    }
    let fileList = [];
    req.files.map((elem) => {
      fileList.push({
        originalname: elem.originalname
      })
    });
    res.json({
      code: '0000',
      type: 'multer',
      fileList: fileList,
      msg: ''
    });
  });
});


router.post('/login', function (req, res, next) {
  db.query("select * from caseinfo where acount=? and pw=?", [req.body.acount, req.body.pw], function (err, results, fields) {
    if (results.length > 0) {
      //这里可以返回token
      vertoken.setToken(req.body.acount, req.body.pw).then(token => {
        return res.json({
          code: 200,
          message: '登录成功',
          token: token
          //前端获取token后存储在localStroage中,
          //**调用接口时 设置axios(ajax)请求头Authorization的格式为`Bearer ` +token
        })
      })
    } else {
      res.json({
        code: 200,
        message: '登录',
      })

    }

  })

});

module.exports = router;